<template>
    <div class="data-analysis">
        <div class="filter-section">
            <a-space>
                <a-select
                    v-model:value="selectedSource"
                    style="width: 200px"
                    placeholder="请选择数据源"
                >
                    <a-select-option 
                        v-for="source in dataSources" 
                        :key="source.id" 
                        :value="source.id"
                    >
                        {{ source.name }}
                    </a-select-option>
                </a-select>

                <a-range-picker
                    v-model:value="dateRange"
                    style="width: 300px"
                />

                <a-button type="primary" @click="fetchAnalysisData">
                    分析数据
                </a-button>
            </a-space>
        </div>

        <div class="statistics-section">
            <a-row :gutter="16">
                <a-col :span="6">
                    <a-card>
                        <template #title>总数据量</template>
                        <div class="statistic-value">
                            {{ formatNumber(statistics.totalData) }}
                        </div>
                        <div :class="['trend', getTrendClass(statistics.dataGrowth)]">
                            较上期: {{ formatTrend(statistics.dataGrowth) }}
                        </div>
                    </a-card>
                </a-col>
                <a-col :span="6">
                    <a-card>
                        <template #title>总互动量</template>
                        <div class="statistic-value">
                            {{ formatNumber(statistics.totalEngagement) }}
                        </div>
                        <div :class="['trend', getTrendClass(statistics.engagementGrowth)]">
                            较上期: {{ formatTrend(statistics.engagementGrowth) }}
                        </div>
                    </a-card>
                </a-col>
                <a-col :span="6">
                    <a-card>
                        <template #title>活跃用户</template>
                        <div class="statistic-value">
                            {{ formatNumber(statistics.activeUsers) }}
                        </div>
                        <div :class="['trend', getTrendClass(statistics.userGrowth)]">
                            较上期: {{ formatTrend(statistics.userGrowth) }}
                        </div>
                    </a-card>
                </a-col>
                <a-col :span="6">
                    <a-card>
                        <template #title>平均互动率</template>
                        <div class="statistic-value">
                            {{ formatPercentage(statistics.engagementRate) }}
                        </div>
                        <div :class="['trend', getTrendClass(statistics.engagementRateGrowth)]">
                            较上期: {{ formatTrend(statistics.engagementRateGrowth) }}
                        </div>
                    </a-card>
                </a-col>
            </a-row>
        </div>

        <div class="charts-section">
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-card title="数据趋势">
                        <div ref="trendChart" style="height: 300px"></div>
                    </a-card>
                </a-col>
                <a-col :span="12">
                    <a-card title="来源分布">
                        <div ref="sourceChart" style="height: 300px"></div>
                    </a-card>
                </a-col>
            </a-row>
            <a-row :gutter="16" style="margin-top: 16px">
                <a-col :span="12">
                    <a-card title="热门话题">
                        <div ref="topicChart" style="height: 300px"></div>
                    </a-card>
                </a-col>
                <a-col :span="12">
                    <a-card title="情感分析">
                        <div ref="sentimentChart" style="height: 300px"></div>
                    </a-card>
                </a-col>
            </a-row>
        </div>

        <div class="ranking-section" style="margin-top: 16px">
            <a-card title="用户排行">
                <a-table :columns="rankingColumns" :data-source="userRankings" :pagination="false">
                    <template #bodyCell="{ column, record }">
                        <template v-if="column.key === 'influence'">
                            <a-progress
                                :percent="record.influence"
                                :stroke-color="getInfluenceColor(record.influence)"
                            />
                        </template>
                    </template>
                </a-table>
            </a-card>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import { analysisApi } from '@/api/analysis'
import { useStore } from 'vuex'

// 状态变量
const store = useStore()
const selectedSource = ref(null)
const dateRange = ref([])
const dataSources = ref([])
const statistics = ref({
    totalData: 0,
    totalEngagement: 0,
    activeUsers: 0,
    engagementRate: 0,
    dataGrowth: 0,
    engagementGrowth: 0,
    userGrowth: 0,
    engagementRateGrowth: 0
})
const userRankings = ref([])

// 图表引用
const trendChart = ref(null)
const sourceChart = ref(null)
const topicChart = ref(null)
const sentimentChart = ref(null)
let trendChartInstance = null
let sourceChartInstance = null
let topicChartInstance = null
let sentimentChartInstance = null

// 表格列定义
const rankingColumns = [
    {
        title: '排名',
        dataIndex: 'index',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
    },
    {
        title: '用户名',
        dataIndex: 'name',
        key: 'name'
    },
    {
        title: '发帖量',
        dataIndex: 'posts',
        key: 'posts'
    },
    {
        title: '互动量',
        dataIndex: 'engagement',
        key: 'engagement'
    },
    {
        title: '影响力',
        dataIndex: 'influence',
        key: 'influence',
        width: 200
    }
]

// 初始化
onMounted(async () => {
    await fetchDataSources()
    initCharts()
})

// 监听图表容器大小变化
watch(
    () => [trendChart.value, sourceChart.value, topicChart.value, sentimentChart.value],
    () => {
        if (trendChartInstance) trendChartInstance.resize()
        if (sourceChartInstance) sourceChartInstance.resize()
        if (topicChartInstance) topicChartInstance.resize()
        if (sentimentChartInstance) sentimentChartInstance.resize()
    }
)

// 获取数据源列表
async function fetchDataSources() {
    try {
        // 检查认证状态
        const isAuthenticated = store.getters.isAuthenticated
        const currentUser = store.getters.currentUser
        console.log('认证状态:', isAuthenticated)
        console.log('当前用户:', currentUser)
        
        const response = await analysisApi.getDataSources()
        console.log('数据源列表:', response)
        dataSources.value = response.results || []
        if (dataSources.value.length > 0) {
            selectedSource.value = dataSources.value[0].id
        }
    } catch (error) {
        console.error('获取数据源列表失败:', error)
        if (!store.getters.isAuthenticated) {
            message.error('请先登录')
            // 可以选择重定向到登录页
            // router.push('/login')
        } else {
            message.error('获取数据源列表失败')
        }
    }
}

// 获取分析数据
async function fetchAnalysisData() {
    if (!selectedSource.value || !dateRange.value?.length) {
        message.warning('请选择数据源和时间范围')
        return
    }

    const params = {
        source_id: selectedSource.value,
        start_date: dateRange.value[0].format('YYYY-MM-DD'),
        end_date: dateRange.value[1].format('YYYY-MM-DD')
    }

    console.log('请求参数:', params)

    try {
        // 获取统计数据
        const dashboardResponse = await analysisApi.getDashboardStats(params)
        console.log('仪表盘数据:', dashboardResponse)
        if (dashboardResponse && typeof dashboardResponse === 'object') {
            statistics.value = {
                totalData: dashboardResponse.total_data || 0,
                totalEngagement: dashboardResponse.total_engagement || 0,
                activeUsers: dashboardResponse.active_users || 0,
                engagementRate: dashboardResponse.engagement_rate || 0,
                dataGrowth: dashboardResponse.data_growth || 0,
                engagementGrowth: dashboardResponse.engagement_growth || 0,
                userGrowth: dashboardResponse.user_growth || 0,
                rateGrowth: dashboardResponse.engagement_rate_growth || 0
            }
        }

        // 获取趋势数据
        const trendResponse = await analysisApi.getTrendData(params)
        console.log('趋势数据:', trendResponse)
        if (trendResponse && typeof trendResponse === 'object') {
            updateTrendChart({
                dates: trendResponse.dates || [],
                data: trendResponse.data || [],
                engagement: trendResponse.engagement || [],
                growth: trendResponse.growth || 0
            })
        }

        // 获取来源分布
        const sourceResponse = await analysisApi.getSourceDistribution(params)
        console.log('来源分布数据:', sourceResponse)
        if (sourceResponse && typeof sourceResponse === 'object' && sourceResponse.data) {
            updateSourceChart(sourceResponse.data)
        }

        // 获取话题分析
        const topicResponse = await analysisApi.getTopicAnalysis(params)
        console.log('话题分析数据:', topicResponse)
        if (topicResponse && typeof topicResponse === 'object' && topicResponse.data) {
            updateTopicChart(topicResponse.data)
        }

        // 获取情感分析
        const sentimentResponse = await analysisApi.getSentimentAnalysis(params)
        console.log('情感分析数据:', sentimentResponse)
        if (sentimentResponse && typeof sentimentResponse === 'object' && sentimentResponse.data) {
            updateSentimentChart(sentimentResponse.data)
        }

        // 获取用户排行
        const rankingResponse = await analysisApi.getUserRankings(params)
        console.log('用户排行数据:', rankingResponse)
        if (rankingResponse && typeof rankingResponse === 'object' && rankingResponse.data) {
            userRankings.value = rankingResponse.data
        }
    } catch (error) {
        console.error('API错误详情:', error)
        message.error('获取分析数据失败：' + error.message)
    }
}

// 初始化图表
function initCharts() {
    trendChartInstance = echarts.init(trendChart.value)
    sourceChartInstance = echarts.init(sourceChart.value)
    topicChartInstance = echarts.init(topicChart.value)
    sentimentChartInstance = echarts.init(sentimentChart.value)
}

// 更新趋势图表
function updateTrendChart(data) {
    console.log('更新趋势图表，数据:', data)
    if (!trendChartInstance) return
    
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            }
        },
        legend: {
            data: ['数据量', '互动量']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: data.dates
        },
        yAxis: [
            {
                type: 'value',
                name: '数据量',
                position: 'left'
            },
            {
                type: 'value',
                name: '互动量',
                position: 'right'
            }
        ],
        series: [
            {
                name: '数据量',
                type: 'line',
                smooth: true,
                data: data.data
            },
            {
                name: '互动量',
                type: 'line',
                smooth: true,
                yAxisIndex: 1,
                data: data.engagement
            }
        ]
    }
    trendChartInstance.setOption(option)
}

// 更新来源分布图表
function updateSourceChart(data) {
    console.log('更新来源分布图表，数据:', data)
    if (!sourceChartInstance) return
    
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [
            {
                type: 'pie',
                radius: '50%',
                data: data.map(item => ({
                    name: item.name,
                    value: item.value
                })),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    }
    sourceChartInstance.setOption(option)
}

// 更新话题图表
function updateTopicChart(data) {
    console.log('更新话题分析图表，数据:', data)
    if (!topicChartInstance) return
    
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value'
        },
        yAxis: {
            type: 'category',
            data: data.map(item => item.name)
        },
        series: [
            {
                type: 'bar',
                data: data.map(item => item.value)
            }
        ]
    }
    topicChartInstance.setOption(option)
}

// 更新情感分析图表
function updateSentimentChart(data) {
    console.log('更新情感分析图表，数据:', data)
    if (!sentimentChartInstance) return
    
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [
            {
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '20',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: data.map(item => ({
                    name: item.name,
                    value: item.value
                }))
            }
        ]
    }
    sentimentChartInstance.setOption(option)
}

// 格式化函数
function formatNumber(value) {
    return value?.toLocaleString() || '0'
}

function formatPercentage(value) {
    return value ? value.toFixed(2) + '%' : '0%'
}

function formatTrend(value) {
    if (!value) return '0%'
    return (value > 0 ? '+' : '') + value.toFixed(2) + '%'
}

function getTrendClass(value) {
    if (!value) return ''
    return value >= 0 ? 'trend-up' : 'trend-down'
}

function getInfluenceColor(value) {
    if (value >= 80) return '#f50'
    if (value >= 60) return '#faad14'
    if (value >= 40) return '#1890ff'
    return '#52c41a'
}
</script>

<style scoped>
.data-analysis {
    padding: 24px;
}

.filter-section {
    margin-bottom: 24px;
}

.statistics-section {
    margin-bottom: 24px;
}

.statistic-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 8px;
}

.trend {
    font-size: 14px;
}

.trend-up {
    color: #52c41a;
}

.trend-down {
    color: #f5222d;
}

.charts-section {
    margin-bottom: 24px;
}

:deep(.ant-card-head) {
    min-height: 48px;
}

:deep(.ant-card-head-title) {
    padding: 8px 0;
}
</style> 